<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License 
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: StoreinfoController.php 465 2012-02-12 05:33:23Z beimuaihui $
 */



class Mall_StoreinfoController extends Baogg_Controller_Action {

	function init() 
	{
		//Zend_Loader::loadClass ( 'UserInfo' );
		
		//$model_id=$this->getRequest()->getParam('model_id',0);
		//$this->userinfo = new UserInfo ($model_id);
		
		//$this->model=new ModelTable($model_id);
		
		//Baogg_Language::loadFile($this->model->getName());
	}

	/**
	 * The default action
	 */
	public function listAction() {
		global $LANG;
		
		//Zend_Loader::loadClass('User');
		//$user=new User();
		
		$params=$this->getRequest()->getParams();
		$form_url=$params;
		//$model_id=$this->getRequest()->getParam('model_id');
		$store_id=(int)$params['store_id'];
		$category_id=$params['category_id'];
		//$user_group_id=$_SESSION['admin']['user_group_role']['user_group_id']?$_SESSION['admin']['user_group_role']['user_group_id']:$_SESSION['admin']['user']['user_id'];
		//		echo '<pre>';print_r($_REQUEST);exit;
		
		
		$Category=new Category();
		$Model=new Model();
		$rs_category=$Category->getList(array("category_pids"=>"%,{$category_id},%","state"=>1,"model_id>0"),array("sort"=>"ordering","dir"=>"asc"));
		//echo '<pre>';print_r($rs_category);exit;
		$form_url['action']='data';
		$form=new Baogg_View_Extform(array("url"=>$form_url),array(),array("region"=>'center','hidden'=>false,"modal"=>false,'autoScroll'=>true));
		$items_category=array(); //store all array(category_id=>model_fields)
		$category_pids="";
		foreach((array)$rs_category as $v_category){
			//echo '<pre>';print_r( $v_category);
			if(!$v_category['model_id']){				
				continue;
			}
			$ModelTable=new ModelTable($v_category['model_id']);
			$rs_model=$ModelTable->getList(array("store_id"=>$store_id,"category_id"=>$v_category['category_id']));
			$rs_row=array();
			if($rs_model){
				$rs_row=$rs_model[0];
			}
			
			$model_id=(int)$v_category['model_id'];
			Zend_Loader::loadClass('ModelField');
			$modelField=new ModelField();
			$rs=$modelField->getList(array("model_id"=>$model_id,"state"=>1),array("sort"=>"ordering","dir"=>"asc"));			
			
			
			//$form->addItem(0,array("name"=>"cols[{$v['category_id']}][store_id]",'xtype'=>'hidden','value'=>$v['store_id']));
			
			
			$items=array();
			foreach((array)$rs as $k=>$v){
							
				$item=array("xtype"=>$v['field_view'],
					"fieldLabel"=>$v['show_name'],
					"name"=> "fields-{$v_category['category_id']}-{$v['field_name']}",//can't use []
					"anchor"=> '95%',
					"init_value" =>$v['init_value']
				);     
				
				
				if( isset($rs_row[$v['field_name']])){
					$item['value']=$rs_row[$v['field_name']];
				}else if($v['field_name']=='category_id'){
					$item['value']=$v_category['category_id'];
				}else if( isset($params[$v['field_name']])){
					$item['value']=$params[$v['field_name']];
				}
				
				
				
				if(in_array($v['field_view'],array('combo','radiogroup','checkboxgroup'))){
					if($item['value']!==""){
						$item['value']="".$item['value'];
					}
					$item_option=ModelTable::handleFieldOptions($v['field_options'],$params);							
					$item=array_merge($item,$item_option);
				
				}else if($v['field_view']=='htmleditor'){
					$item['height']='300';
					$item['width']='600';
					unset($item['anchor']);
				}
				$items[]=$form->handleItem($item);
			}

			$items_category[$v_category['category_id']]['items']=$items;
			$category_pids.=$v_category['category_pids'];
		}
		
		//generate category tree
		$arr_category_pids=array_filter(array_unique(explode(",",$category_pids)));
		$category_names=$Category->getList(array("category_id"=>$arr_category_pids),null,null,array("category_id","category_name","category_pid"));
		foreach((array)$category_names as $k=>$v){
			if(isset($items_category[$v['category_id']])){
				$category_names[$k]['items']=$items_category[$v['category_id']]['items'];
			}
		}
		
		$Tree=new Baogg_Db_Tree();
		$category_names=$Tree->rs2GridTree($category_names);
		//echo '<pre>';print_r($category_names);exit;
		$Tree->tr2Fieldset($category_names);	////convert to fieldset tree	

		//echo '<pre>';print_r($category_names);exit;
		$form->addItem(0,$category_names[0][0]);
		unset($category_names);
		$form->addExistButtons(array('save','-','cancel'));//,'config','config'
					
		$this->view->form=$form;
		//	$json_field_items=Zend_Json::encode($field_items);
		
		
		//$cm['sub_table']=array("hidden"=>true,"cmType"=>Baogg_View_Extgrid::CMTYPE_SUBTABLE) ; //Baogg_View_Extgrid::;
		
		
		
		//$this->view->form_url=BAOGG_BASE_URL."mall/userinfo/save/model_id/{$model_id}";
		$this->view->LANG=Zend_Json::encode($LANG);

		
		
		

	}

	/**
	 * The data action
	 */
	function dataAction() {	
		
		$ret=array("success"=>false,"msg"=>"save_fail");
	    $post=$this->_request->getPost ();
	    $params=$this->getRequest()->getParams();
	    //echo '<pre>';print_r($params);exit;
	    
	    //decode _POST[fields_(category_id)_(field_name)] to $fields[category_id][field_name]
	   $fields=array();
	    foreach((array)$post as $k=>$v){
	    	$arr_k=explode("-",$k);
	    	if(count($arr_k)==3 && $arr_k[0]=='fields'){
	    		if(isset($fields[$arr_k[1]])){
	    			$fields[$arr_k[1]][$arr_k[2]]=$v;
	    		}else{
	    			$fields[$arr_k[1]]=array($arr_k[2]=>$v);
	    		}
	    	}
	    }
		
	    
	    //check form		
	   if(!$fields || !is_array($fields)){
	   	   echo Baogg_Language::outputResult($ret);
		   exit;
	   }
	   //echo '<pre>';print_r($fields);exit;
	   $Category=new Category();
	    foreach($fields as $category_id=>$arr_field_name){
	    	$rs_category=$Category->getOne($category_id);
	    	if($rs_category && $rs_category[0]['model_id']){
	    		$ModelTable=new ModelTable($rs_category[0]['model_id']);
	    		if(isset($arr_field_name[$ModelTable->myPrimary]) && $arr_field_name[$ModelTable->myPrimary]){
	    			$ModelTable->_update($arr_field_name,$arr_field_name[$ModelTable->myPrimary]);
	    		}else{
	    			$ModelTable->_insert($arr_field_name);
	    		}
	    		
	    		$ret['success'] = true;				
				$ret['msg'] = "save_ok";
	    	}
	    }
	    
	    echo Baogg_Language::outputResult($ret);
		
		$this->_helper->viewRenderer->setNoRender ();
	}

	
	/**
	 * The add action
	 */
	function addAction(){	
		
		$this->saveAction();
		
	}
	
	/**
	 * The edit action
	 */
	function editAction() {
		$this->saveAction();
	}

	/**
	 * The delete action
	 */
	function deleteAction() {
        
	    $ret=array("success"=>false,"msg"=>"delete_fail");
	    $id = Baogg_Controller_Action::_getParam ( 'ids' );
		
		$flag=$this->model->_delete($id);

		//echo Baogg_Db::debugDb(Zend_Registry::get('db'));
		
		if ($flag){
			$ret['success'] = true;
			$ret["msg"]="delete_ok";
		}
		
		echo Baogg_Language::outputResult($ret);
		 $this->_helper->viewRenderer->setNoRender ();
		
		
	}
	
	function removeAction(){
		$this->deleteAction();
	}
	
	/**
	 * The save action
	 */
	function saveAction() {
		//global $LANG;
	
	    $ret=array("success"=>false,"msg"=>"save_fail");
	    
	    //check form
		if (!$this->_request->isPost ())
		{
		   echo Baogg_Language::outputResult($ret);
		   exit;
		}
		
		if($_FILES){
			$Attachment=new Attachment();
			$ret=$Attachment->upload($this->getRequest()->getParams());
			if(isset($ret['flag']) && !$ret['flag']){
				echo Baogg_Language::outputResult($ret);
				exit; 
			}
		}
		
		$formData = $this->_request->getPost ();
		$params=$this->getRequest()->getParams();
		
		if(!$formData)
		{
		   echo Baogg_Language::outputResult($ret);
		   exit;     
		}
		
		
		
		 //filter group id
	    $user=new User();
	    /*if(!$user->isAdmin())
	    {
	    	
		    $permission=new Permission();
		    $arr_group_id=$permission->check('model','model_id',$params['model_id'],$_SESSION['admin']['user_group_role']['role_id'],$params['action']);        	
	        if($arr_group_id!==false){
	        	$is_include_self=in_array("0",$arr_group_id);
				$arr_group_id=array_filter($arr_group_id);		
				Zend_Loader::loadClass('UserGroup');
				$userGroup=new UserGroup();
				$arr_group_id=$userGroup->getWithChildIds($arr_group_id);			        	
	        }	       
	       // echo '<pre>';var_dump($formData['user_id']);echo __FILE__;exit;
	        $rs_user=$user->getOne($formData['user_id']);
	        if($arr_group_id && in_array($rs_user[0]['user_group_id'],$arr_group_id) || $is_include_self && $formData['user_id']==$_SESSION['admin']['user']['user_id']){
	        	
	        }else{
	        	echo  Zend_Json::encode(array("count"=>0,"data"=>array()));
	        	exit;
	        }	
	    }	*/
		
		$arr_model=$this->model->filterForm($formData);
		
		
		// echo '<pre>';print_r($arr);print_r($arr_model);exit;
		$rs = $this->model->getSame($arr_model);
		if($params['action']=='edit'){
			//update record
			//$permission_type = 2;
			//echo '<pre>';print_r($rs);print_r($arr_model);exit;
			if(!$rs ||  (count($rs)==1 &&  $rs[0] == $arr_model["id"] )){
			    $this->model->update($arr_model, "id={$arr_model['id']}");
			    $ret['success'] = true;				
				$ret['msg'] = "save_ok";			
			}else{
				$ret['msg'] = "exist_same_record";
			}
			
		}else{
			//insert record
			//$permission_type = 1;			
			if($rs){				
				$ret['msg'] = "exist_same_record";
			}else{
			    unset($arr_model["id"]);
				$ret['success'] =$this->model->insert($arr_model)?true:false;
				
				$ret['msg'] = "add_ok";
			}
		}
				
		echo Baogg_Language::outputResult($ret);
		//echo Baogg_Db::debugDb(Zend_Registry::get('db'));exit;
		$this->_helper->viewRenderer->setNoRender ();
		
		
	}
	


}
